package com.liu.controller;

import com.github.pagehelper.PageInfo;
import com.liu.model.Book;
import com.liu.service.BookService;
import com.liu.tools.ActionContextUtils;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by liu on 2018/3/26.
 */
@RestController
@RequestMapping(value = "/book")
public class BookController {

    @Autowired
    private BookService bookService;

    @ResponseBody
    @PostMapping(value = "/add", produces = {"application/json;charset=UTF-8"})
    public String add(HttpServletRequest req, Book book) {
        bookService.add(book);
        return "success";
    }

    @ResponseBody
    @PostMapping(value = "/edit", produces = {"application/json;charset=UTF-8"})
    public String edit(HttpServletRequest req, Book book) {
        book.setUpdateTime(new Date());
        bookService.edit(book);
        return "success";
    }


    @RequestMapping(value = "/list", produces = {"application/json;charset=UTF-8"})
    public PageInfo findAllBook(int pageNum, int pageSize) {
        Map<String, Object> queryMap = new HashMap<String, Object>(0);
        String borrowStatus = ActionContextUtils.getParameter("borrowStatus");
        String bookName = ActionContextUtils.getParameter("bookName");
        String bookInfoId = ActionContextUtils.getParameter("bookInfoId");
        if (borrowStatus != null && !borrowStatus.equals("")) {
            queryMap.put("borrowStatus", borrowStatus);
        }
        if (bookName != null && !bookName.equals("")) {
            queryMap.put("bookName", bookName);
        }
        if (bookInfoId != null && !bookInfoId.equals("")) {
            queryMap.put("bookInfoId", bookInfoId);
        }
        List<Book> list = bookService.findAll(pageNum, pageSize, queryMap);
        return new PageInfo(list);
    }

    @RequestMapping(value = "/detail", produces = {"application/json;charset=UTF-8"})
    public Book findBook(String id) {
        Book book = bookService.findById(id);
        return book;
    }

    @ResponseBody
    @PostMapping(value = "/delete", produces = {"application/json;charset=UTF-8"})
    public String del(String id) {
        bookService.deleteById(id);
        return "success";
    }
}